package com.cloudrui.service.wechat.neteasy;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.cloudrui.service.wechat.neteasy.bean.LiveBean;
import com.cloudrui.service.wechat.neteasy.bean.Matches;

import cn.zhouyafeng.itchat4j.core.Core;
import cn.zhouyafeng.itchat4j.utils.MyHttpClient;

public class NetEasyMatchService {

	private static String baseUrl = "http://nba.sports.163.com/";
	private static String liveUrl = "http://data.live.126.net/live/";
	private static String jsonSuffix = ".json";
	
	private static String match= "/match/daily/";
	private static String html = ".html";
	public static void main(String[] args) {
	
	}
	
	public static LiveBean getLiveBean(String name) {
		Matches m = getMatches(name);
		if(m==null)return null;
		long roomId = m.getRoomId();
		if(roomId!=0) {
			String url = liveUrl + roomId + jsonSuffix;
			LiveBean lb = new LiveBean();
			lb.setUrl(url);
			lb.setMcode(m.getMcode()+"");
			return lb;
		}
		return null;
	}
	
	public static Matches getMatches(String name) {
		List<Matches> match = getTodayMatch();
		if(match == null) {
			return null;
		}
		for(Matches m:match) {
			if(m.getAwayFullName().contains(name)||m.getHomeFullName().contains(name)) {
				return m;
			}
		}
		return null;
	}
	
	public static  List<Matches> getTodayMatch() {
		MyHttpClient myHttpClient = Core.getInstance().getMyHttpClient();
		String url = getTodayUrl();
		HttpEntity entity =myHttpClient.doGet(url, null, false, null);
		String result = null;
		try {
			result = EntityUtils.toString(entity, "UTF-8");
		} catch (ParseException | IOException e) {
			e.printStackTrace();
			return null;
		}
		return JSON.parseArray(result, Matches.class);

	}
	
	private static String getTodayUrl() {
		//http://nba.sports.163.com/2017/match/daily/20171125.html
		StringBuffer sb = new StringBuffer(baseUrl);
		Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT-8:00"));
		int year = c.get(Calendar.YEAR);
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.CHINA);
		String date = format.format(c.getTime());
		sb.append(year);
		sb.append(match);
		sb.append(date);
		sb.append(html);
		
		return sb.toString();
	}

}
